from django.db.transaction import atomic
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.viewsets import ModelViewSet
from .serializers import OrgSerializer, HostSerializer, TrackSerializer
from .models import Organization, Host, Track
from rest_framework.decorators import action
from rest_framework.response import Response
from django.core.cache import cache
from .filters import HostFilter
from rest_framework.filters import SearchFilter


class OrgViewSet(ModelViewSet):
    queryset = Organization.objects.all()
    serializer_class = OrgSerializer
    org_nodes_cache_key = "tree_orgs"

    def get_queryset(self):
        return super().get_queryset().filter(is_deleted=False)

    @action(detail=False)
    def all(self, request):
        if cache.get(self.org_nodes_cache_key) is None:
            queryset = self.filter_queryset(self.get_queryset())
            serializer = self.get_serializer(queryset, many=True)
            cache.set(self.org_nodes_cache_key, serializer.data)
        return Response(cache.get(self.org_nodes_cache_key))

    def create(self, request, *args, **kwargs):
        response = super().create(request, *args, **kwargs)
        cache.delete(self.org_nodes_cache_key)
        return response

    def update(self, request, *args, **kwargs):
        response = super().update(request, *args, **kwargs)
        cache.delete(self.org_nodes_cache_key)
        return response

    def destroy(self, request, *args, **kwargs):
        response = super().destroy(request, *args, **kwargs)
        cache.delete(self.org_nodes_cache_key)
        return response

    @action(['patch'], True)
    def descendants(self, request, pk=None):
        with atomic():
            Host.objects.filter(org__in=request.data['ids']).update(is_deleted=True)
            self.get_queryset().filter(pk__in=request.data['ids']).update(is_deleted=True)
        cache.delete(self.org_nodes_cache_key)
        return Response(status=204)


class HostViewSet(ModelViewSet):
    queryset = Host.objects.all()
    serializer_class = HostSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_class = HostFilter

    def get_queryset(self):
        return super().get_queryset().filter(is_deleted=False)

class TrackViewSet(ModelViewSet):
    queryset = Track.objects.all()
    serializer_class = TrackSerializer
    filter_backends = [SearchFilter]
    search_fields = ['user__username']